package com.item.mofan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.item.mofan.common.Result;
import com.item.mofan.dto.DishDto;
import com.item.mofan.entity.Category;
import com.item.mofan.entity.Dish;
import com.item.mofan.entity.DishFlavor;
import com.item.mofan.entity.Employee;
import com.item.mofan.service.CategoryService;
import com.item.mofan.service.DishFlavorService;
import com.item.mofan.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 菜品添加功能
     * @param dishDto
     * @return
     */
    @PostMapping
    public Result<String> save(@RequestBody DishDto dishDto){
        dishService.saveWithFlavor(dishDto);
        redisTemplate.delete("dish_"+dishDto.getCategoryId());
        return Result.success("菜品添加成功");
    }
    /**
     * 分页条件功能
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public Result<Page> page(int page, int pageSize,String name){

        Page<Dish> dishPage=new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage=new Page<>(page,pageSize);

        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName,name);
        dishService.page(dishPage, queryWrapper);

        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");//对象拷贝，records除外

        List<Dish> dishList=dishPage.getRecords();//获取Dish的List数据

        List<DishDto> dishDtoList=dishList.stream().map((item)->{
            DishDto dishDto =new DishDto();

            BeanUtils.copyProperties(item,dishDto);//把item数据拷贝给dishDto对象

            //根据id查找出菜品名称
            Long id=item.getCategoryId();
            Category category = categoryService.getById(id);
            if (category!=null){
                dishDto.setCategoryName(category.getName());//名称赋值给dishDto对象
            }
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(dishDtoList);

        return Result.success(dishDtoPage);
    }

    /**
     * 回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return Result.success(dishDto);
    }

    /**
     * 更新功能
     * @param dishDto
     * @return
     */
    @PutMapping
    public Result<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
        redisTemplate.delete("dish_"+dishDto.getCategoryId());
        return Result.success("菜品更新成功");
    }

    /**
     * 菜品分类列表展示(redis缓存菜品）
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public Result<List<DishDto>> list(Dish dish){
        List<DishDto> dishDtoList=null;

        String key="dish_"+dish.getCategoryId();
        dishDtoList= (List<DishDto>) redisTemplate.opsForValue().get(key);//获取缓存数据
        //如果redis存在缓存数据
        if (dishDtoList!=null){
            return Result.success(dishDtoList);
        }

        LambdaQueryWrapper<Dish>  queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());//展示该分类的菜品
        queryWrapper.eq(Dish::getStatus,1);//展示售卖的菜品
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> dishList=dishService.list(queryWrapper);

        dishDtoList=dishList.stream().map((item)->{
            DishDto dishDto =new DishDto();

            BeanUtils.copyProperties(item,dishDto);//把item数据拷贝给dishDto对象
            LambdaQueryWrapper<DishFlavor> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getDishId,dishDto.getId());
            List<DishFlavor> flavors=dishFlavorService.list(queryWrapper1);

            dishDto.setFlavors(flavors);

            return dishDto;
        }).collect(Collectors.toList());

        redisTemplate.opsForValue().set(key,dishDtoList,1, TimeUnit.HOURS);

        return Result.success(dishDtoList);
    }

    @DeleteMapping
    public Result<String> delete(@RequestParam List<Long> ids){
        for (int i = 0; i < ids.size(); i++) {
            Long id= ids.get(i);
            Dish dish = dishService.getById(id);
            redisTemplate.delete("dish_"+dish.getCategoryId());
        }
        dishService.removeWithFlavor(ids);

        return Result.success("删除菜品成功");
    }
    @PostMapping("/status/1")
   public Result<String> up(@RequestParam List<Long> ids){
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getId,ids);
        List<Dish> dishList=dishService.list(queryWrapper);
        dishList.stream().map((item)->{
            item.setStatus(1);
            return item;
        }).collect(Collectors.toList());

       dishService.updateBatchById(dishList);
        Set key=redisTemplate.keys("dish_*");
        redisTemplate.delete(key);
       return Result.success("菜品上架成功");
    }
    @PostMapping("/status/0")
    public Result<String> down(@RequestParam List<Long> ids){
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getId,ids);
        List<Dish> dishList=dishService.list(queryWrapper);
        dishList.stream().map((item)->{
            item.setStatus(0);
            return item;
        }).collect(Collectors.toList());

        dishService.updateBatchById(dishList);
        Set key=redisTemplate.keys("dish_*");
        redisTemplate.delete(key);
        return Result.success("菜品下架成功");
    }
}
